package com.wy.sloth.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * 网络相关工具类
 * 
 * @author wangyuan
 * @since 2019年4月8日
 */
public class NetUtils {

    /**
     * 获取本机（window或linux机器）的IP地址
     * @return
     * @throws UnknownHostException
     */
    public static String getHostAddress() throws UnknownHostException {
        try {
            InetAddress candidateAddress = null;
            Enumeration<NetworkInterface> networkEnumeration = NetworkInterface.getNetworkInterfaces();
            while(networkEnumeration.hasMoreElements()){
                Enumeration<InetAddress> inetAddressEnumeration = networkEnumeration.nextElement().getInetAddresses();
                InetAddress tempAddress = null;
                while(inetAddressEnumeration.hasMoreElements()){
                    tempAddress = inetAddressEnumeration.nextElement();
                    if(tempAddress.isLoopbackAddress()){
                        continue;
                    }
                    
                    if(tempAddress.isSiteLocalAddress()){
                        return tempAddress.getHostAddress();
                    }
                    
                    if(candidateAddress == null){
                        candidateAddress = tempAddress;
                    }
                }
            }
            
            if(candidateAddress != null){
                return candidateAddress.getHostAddress();
            }
            
            InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
            if (jdkSuppliedAddress == null) {
                throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
            }
            return jdkSuppliedAddress.getHostAddress();
        } catch (Exception e) {
            throw new UnknownHostException("Failed to determine LAN address: " + e);
        }
    }
}
